package com.threegroup.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.threegroup.admin.dao.SysRoleMenuDao;
import com.threegroup.admin.entity.SysRoleMenuEntity;
import com.threegroup.admin.service.ISysRoleMenuService;
import com.threegroup.common.constant.Constant;
import com.threegroup.common.utils.RequestHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 角色菜单服务接口实现类
 */
@Service
public class SysRoleMenuServiceImpl implements ISysRoleMenuService {

    @Resource
    private SysRoleMenuDao sysRoleMenuDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(Long roleId, List<Long> menuIdList) {

        HttpServletRequest request = RequestHolder.getRequest();
        Long userId = Long.parseLong(request.getAttribute(Constant.USER_ID).toString());

        //先删除角色菜单关系
        deleteByRoleIds(new Long[]{roleId});

        //角色没有一个菜单权限的情况
        if(CollUtil.isEmpty(menuIdList)){
            return ;
        }

        //保存角色菜单关系
        for(Long menuId : menuIdList){
            SysRoleMenuEntity sysRoleMenuEntity = new SysRoleMenuEntity();
            sysRoleMenuEntity.setMenuId(menuId);
            sysRoleMenuEntity.setRoleId(roleId);
            sysRoleMenuEntity.setCreator(userId);
            sysRoleMenuEntity.setCreateDate(new Date());

            //保存
            sysRoleMenuDao.insert(sysRoleMenuEntity);
        }
    }

    @Override
    public List<Long> getMenuIdList(Long roleId){
        return sysRoleMenuDao.getMenuIdList(roleId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByRoleIds(Long[] roleIds) {
        sysRoleMenuDao.deleteByRoleIds(roleIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByMenuId(Long menuId) {
        sysRoleMenuDao.deleteByMenuId(menuId);
    }

}
